<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>电子书管理</title>
    <link href="../css/quill.snow.css" rel="stylesheet" />
    <script src="../js/quill.js"></script>
    <style>
      /* 复用现有样式 */
      body {
        font-family: "Microsoft YaHei", sans-serif;
        padding: 20px;
        background: white;
        overflow: hidden; /* 禁用全局滚动条 */
      }

      .container {
        display: flex;
        height: 100vh;
        width: 100%;
        overflow: hidden; /* 确保没有滚动条 */
      }

      .sidebar {
        width: 200px;
        background: #f5f5f5;
        padding: 20px;
        border-right: 1px solid #ddd;
        flex-shrink: 0;
        overflow-y: auto; /* 允许垂直滚动 */
        overflow-x: hidden;
      }

      .main-content {
        flex: 1;
        padding: 20px;
        overflow-y: auto; /* 允许垂直滚动 */
      }

      .book-list {
        list-style: none;
        padding: 0;
        margin: 0;
        width: 100%;
      }

      .book-item {
        padding: 10px;
        margin: 5px 0;
        cursor: pointer;
        border-radius: 4px;
        display: flex;
        align-items: center;
        gap: 10px;
        width: 100%;
        box-sizing: border-box;
      }

      .book-item:hover {
        background: #f5f5f5;
      }

      .book-item.active {
        background: #8b0000;
        color: white;
      }

      .editor-container {
        height: calc(100vh - 180px);
      }

      .toolbar {
        padding: 10px;
        background: #f8f8f8;
        border-bottom: 1px solid #ddd;
      }

      .btn {
        padding: 8px 16px;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        margin-right: 10px;
        background: #8b0000;
        color: white;
      }

      .btn:hover {
        background: #a00000;
      }

      .editor-wrapper {
        flex: 1;
        overflow-y: hidden; /* 允许垂直滚动 */
        margin-right: 20px;
        height: 100%; /* 确保高度适配 */
      }

      #editor-container {
        height: 100%; /* 确保高度适配 */
        background: white;
        border: 1px solid #ddd;
        border-radius: 4px;
        width: 100%;
        padding: 40px;
        box-sizing: border-box;
      }

      .success-tip {
        display: none;
        color: green;
        margin-left: 10px;
      }

      /* 在已有样式后添加 */
      .title-input {
        padding: 8px;
        border: 1px solid #ddd;
        border-radius: 4px;
        width: 200px;
        margin-right: 10px;
        font-size: 14px;
      }

      /* 添加到现有样式中 */
      .preview-list {
        display: flex;
        flex-direction: column;
        gap: 20px;
        padding: 10px 0;
        width: 100%;
        box-sizing: border-box;
      }

      .preview-item {
        width: 100%;
        border: 1px solid #ddd;
        padding: 8px;
        border-radius: 4px;
        box-sizing: border-box;
        margin: 0;
      }

      .preview-item .page-title {
        text-align: center;
        margin-bottom: 8px;
        font-weight: bold;
        color: #666;
        font-size: 14px; /* 减小字体大小 */
      }

      .preview-item img {
        width: 100%;
        height: auto;
        border-radius: 4px;
        max-width: 100%;
        display: block;
      }

      /* 修改 book-item 相关样式 */
      .book-cover {
        width: 50px;
        height: 70px;
        object-fit: cover;
        border-radius: 4px;
        background: #eee;
      }

      .book-info {
        flex: 1;
      }

      .book-title {
        flex: 1;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        font-size: 14px;
        line-height: 1.4;
        padding-right: 10px;
      }

      /* 修改现有样式 */
      .content-preview-container {
        display: flex;
        gap: 20px;
        flex: 1;
        overflow: hidden;
      }

      /* 确保编辑器内容区域可以正常显示和编辑 */
      .ql-container {
        height: calc(100% - 42px) !important;
      }

      .ql-editor {
        height: 100%; /* 确保编辑器内容区域适配 */
        overflow-y: auto;
        padding: 40px !important;
        font-size: 16px !important;
        line-height: 1.5 !important;
        width: 100% !important;
        box-sizing: border-box !important;
        max-width: 800px;
        margin: 0 auto;
      }

      /* 书籍列表中的标题样式 - 省略显示 */
      .book-list .book-title {
        flex: 1;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        font-size: 14px;
        line-height: 1.4;
        padding-right: 10px;
      }

      /* 编辑区域的标题样式 - 完整显示 */
      .toolbar .book-title {
        font-size: 16px;
        line-height: 1.5;
        padding: 10px;
        width: 100%;
        white-space: normal; /* 允许换行 */
        word-break: break-all; /* 允许在任意字符间换行 */
      }

      /* 预览弹层样式 */
      .preview-modal {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.5);
        z-index: 1000;
      }

      .preview-modal-content {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background: white;
        padding: 20px;
        border-radius: 8px;
        width: 80%;
        max-width: 1000px;
        max-height: 80vh;
        overflow-y: auto;
      }

      .preview-modal-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
      }

      .preview-modal-close {
        cursor: pointer;
        font-size: 24px;
        color: #666;
      }

      /* 添加提示样式 */
      .progress-mask {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, 0.5);
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 1000;
      }

      .progress-container {
        background: white;
        padding: 20px 40px;
        border-radius: 8px;
        text-align: center;
        animation: fadeIn 0.3s ease;
      }

      @keyframes fadeIn {
        from {
          opacity: 0;
          transform: translateY(-20px);
        }
        to {
          opacity: 1;
          transform: translateY(0);
        }
      }

      /* 修改保存按钮样式 */
      .save-btn {
        background: #1a73e8;
        color: white;
        border: none;
        padding: 8px 16px;
        border-radius: 4px;
        cursor: pointer;
      }

      .save-btn:hover {
        background: #1557b0;
      }
    </style>
  </head>
  <body>
    <h2>电子书管理</h2>

    <div class="container">
      <div class="sidebar">
        <div class="book-list" id="bookList">
          <!-- 电子书列表将通过 JavaScript 动态加载 -->
        </div>
      </div>

      <div class="main-content">
        <div class="editor-container">
          <div class="toolbar">
            <input
              type="text"
              id="bookTitle"
              class="title-input"
              placeholder="请输入标题"
            />
            <button onclick="saveBook()" class="btn">保存</button>
            <button
              onclick="document.getElementById('coverFile').click()"
              class="btn"
            >
              设置封面
            </button>
            <input
              type="file"
              id="coverFile"
              accept="image/*"
              style="display: none"
            />
            <span id="successTip" class="success-tip">保存成功！</span>
          </div>
          <div class="content-preview-container">
            <div class="editor-wrapper">
              <div id="editor-container">
                <!-- 添加一个初始的空段落，确保编辑器有内容可编辑 -->
                <p><br /></p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 预览弹层 -->
    <div id="previewModal" class="preview-modal">
      <div class="preview-modal-content">
        <div class="preview-modal-header">
          <h3>内容预览</h3>
          <span class="preview-modal-close" onclick="hidePreview()"
            >&times;</span
          >
        </div>
        <div class="preview-list" id="previewList"></div>
      </div>
    </div>

    <script>
      let editor;
      let currentBookId;

      // 初始化编辑器
      function initEditor() {
        const editorConfig = {
          theme: "snow",
          modules: {
            toolbar: [
              // 字体选择
              [{ font: [] }],

              // 标题（1, 2）
              [{ header: "1" }, { header: "2" }],

              // 字号选择
              [{ size: ["small", "normal", "large", "huge"] }],

              // 字体加粗、斜体、下划线、删除线
              ["bold", "italic", "underline", "strike"],

              // 列表：有序列表、无序列表、缩进
              [{ list: "ordered" }, { list: "bullet" }],
              [{ indent: "-1" }, { indent: "+1" }],

              // 对齐方式：左对齐、居中、右对齐、两端对齐
              [{ align: [] }],

              // 链接插入
              ["link"],

              // 引用
              ["blockquote"],

              // 图片和视频插入
              ["image", "video"],

              // 表格、代码块
              ["code-block"],

              // 颜色选择
              [{ color: [] }, { background: [] }],

              // 上标、下标
              [{ script: "sub" }, { script: "super" }],

              // 清除格式
              ["clean"],

              // 自定义工具：你可以在这里添加自己的按钮
              [{ direction: "rtl" }], // 右到左文本方向
              [{ align: "center" }], // 水平居中
            ],
          },
          placeholder: "请输入内容...",
          bounds: "#editor-container",
        };

        editor = new Quill("#editor-container", editorConfig);

        // 确保编辑器可以获得焦点
        editor.focus();
      }

      // 修改设置内容的方法
      function setContent(content) {
        editor.root.innerHTML = content || "";
      }

      // 修改获取内容的方法
      function getContent() {
        return editor.root.innerHTML;
      }

      // 加载书籍列表
      async function loadBooks() {
        try {
          const response = await fetch("/admin/api/books/list.php");
          const result = await response.json();

          console.log(result);

          if (!result.success) throw new Error(result.message);

          const bookList = document.getElementById("bookList");
          bookList.innerHTML = result.data.books
            .map(
              (book) => `
                    <div class="book-item" onclick="selectBook(${
                      book.id
                    })" data-id="${book.id}">
                        <img 
                            class="book-cover" 
                            src="${
                              book.cover || "../images/default-cover.jpg"
                            }" 
                            onerror="this.src='../images/default-cover.jpg'"
                            alt="${book.title}"
                        >
                        <div class="book-info">
                            <div class="book-title">${book.title}</div>
                        </div>
                    </div>
                `
            )
            .join("");

          // 如果有书籍，自动选中第一本
          if (result.data.books.length > 0) {
            selectBook(result.data.books[0].id);
          }
        } catch (error) {
          console.error("加载失败:", error);
          alert("加载失败，请重试");
        }
      }

      // 选择电子书
      async function selectBook(id) {
        try {
          currentBookId = id;

          // 高亮选中的书籍
          document.querySelectorAll(".book-item").forEach((item) => {
            item.classList.remove("active");
          });
          const selectedBook = document.querySelector(
            `.book-item[data-id="${id}"]`
          );
          if (selectedBook) {
            selectedBook.classList.add("active");
          }

          // 加载书籍内容
          const response = await fetch(`/admin/api/books/get.php?id=${id}`);
          const result = await response.json();

          if (!result.success) throw new Error(result.message);

          // 设置标题和内容
          document.getElementById("bookTitle").value = result.data.title || "";
          setContent(result.data.content || "");

          // 更新预览图列表
          updatePreviewList(result.data.contentImages || []);

          // 重置文件输入元素，确保可以再次选择相同的文件
          const coverFileInput = document.getElementById("coverFile");
          if (coverFileInput) {
            coverFileInput.value = "";
          }
        } catch (error) {
          console.error("加载书籍失败:", error);
          alert("加载书籍失败，请重试");
        }
      }

      // 保存书籍
      async function saveBook() {
        if (!currentBookId) {
          alert("请先选择一本书");
          return;
        }

        let mask = null;
        try {
          const title = document.getElementById("bookTitle").value.trim();
          if (!title) {
            throw new Error("标题不能为空");
          }

          const content = editor.root.innerHTML;

          // 显示保存中提示
          mask = document.createElement("div");
          mask.className = "progress-mask";
          mask.innerHTML = `
              <div class="progress-container">
                  <div>正在准备内容...</div>
              </div>
          `;
          document.body.appendChild(mask);

          // 分页处理内容
          const pages = splitContent(content);
          console.log(`内容已分为${pages.length}页`);
          // 初始化预览图数组
          let contentImages = [];
          let thumbImages = [];

          // 获取封面图片
          const coverImage = document.querySelector(
            `.book-item[data-id="${currentBookId}"] .book-cover`
          );
          if (coverImage) {
            const coverUrl = coverImage.src;
            const coverResponse = await fetch(coverUrl);
            const coverBlob = await coverResponse.blob();
            const coverFile = new File([coverBlob], "cover.jpg", {
              type: "image/jpeg",
            });

            const coverFormData = new FormData();
            coverFormData.append("id", currentBookId);
            coverFormData.append("image", coverFile);
            coverFormData.append("thumb", coverFile);
            coverFormData.append("page", 1);

            const coverUploadResponse = await fetch(
              "/admin/api/books/generate_preview.php",
              {
                method: "POST",
                body: coverFormData,
              }
            );

            const coverResult = await coverUploadResponse.json();
            if (!coverResult.success) {
              throw new Error(coverResult.message || "封面上传失败");
            }

            contentImages.push(coverResult.urls.normal);
            thumbImages.push(coverResult.urls.thumb);
          }

          // 为每一页生成预览图并上传
          for (let i = 0; i < pages.length; i++) {
            const pageImages = await generatePreview(pages[i]);

            // 更新保存进度
            mask.querySelector(".progress-container").innerHTML = `
                <div>正在处理第 ${i + 1} 页，共 ${pages.length} 页</div>
                <div style="font-size: 14px; color: #666; margin-top: 8px;">请耐心等待...</div>
            `;

            // 使用表单格式提交数据
            const formData = new FormData();
            formData.append("id", currentBookId);
            formData.append("image", pageImages.normal);
            formData.append("thumb", pageImages.thumb);
            formData.append("page", i + 2);

            const response = await fetch(
              "/admin/api/books/generate_preview.php",
              {
                method: "POST",
                body: formData,
              }
            );

            const result = await response.json();
            if (!result.success)
              throw new Error(result.message || "保存预览图失败");

            // 分别添加正常图片和缩略图URL到数组
            contentImages.push(result.urls.normal);
            thumbImages.push(result.urls.thumb);
          }

          // 更新保存状态
          mask.querySelector(".progress-container").innerHTML = `
              <div class="progress-container">
                  <div>正在保存所有内容</div>
                  <div style="font-size: 14px; color: #666; margin-top: 8px;">马上就好...</div>
              </div>
          `;

          const response = await fetch("/admin/api/books/save.php", {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify({
              id: currentBookId,
              title: title,
              content: content,
              contentImages: contentImages,
              thumbImages: thumbImages,
            }),
          });

          const result = await response.json();
          if (!result.success) throw new Error(result.message);

          // 保存成功提示
          mask.querySelector(".progress-container").innerHTML = `
              <div class="progress-container">
                  <div style="color: #52c41a; font-size: 16px;">✓ 保存成功</div>
                  <div style="font-size: 14px; color: #666; margin-top: 8px;">所有内容已更新</div>
              </div>
          `;

          // 2秒后关闭提示
          setTimeout(() => {
            if (mask && mask.parentNode) {
              document.body.removeChild(mask);
            }
          }, 2000);

          // 更新列表中的标题
          const bookItem = document.querySelector(
            `.book-item[data-id="${currentBookId}"]`
          );
          if (bookItem) {
            const titleElement = bookItem.querySelector(".book-title");
            if (titleElement) {
              titleElement.textContent = title;
            }
          }
        } catch (error) {
          console.error("保存失败:", error);
          // 显示错误提示
          if (mask) {
            mask.querySelector(".progress-container").innerHTML = `
                <div style="color: #ff4d4f;">保存失败: ${error.message}</div>
            `;
            setTimeout(() => {
              if (mask && mask.parentNode) {
                document.body.removeChild(mask);
              }
            }, 2000);
          }
        }
      }

      // 辅助函数：将 base64 转换为 Blob
      function dataURItoBlob(dataURI) {
        const byteString = atob(dataURI.split(",")[1]);
        const mimeString = dataURI.split(",")[0].split(":")[1].split(";")[0];
        const ab = new ArrayBuffer(byteString.length);
        const ia = new Uint8Array(ab);

        for (let i = 0; i < byteString.length; i++) {
          ia[i] = byteString.charCodeAt(i);
        }

        return new Blob([ab], { type: mimeString });
      }

      // 分页处理内容
      function splitContent(content) {
        const temp = document.createElement("div");
        temp.style.cssText = `
            width: 1080px;  // 匹配阅读器的宽度
            padding: 40px;
            font-size: 24px;
            line-height: 1.5;
            position: absolute;
            left: -9999px;
            box-sizing: border-box;
        `;
        temp.innerHTML = content;
        document.body.appendChild(temp);

        const pages = [];
        const maxHeight = 1440; // 匹配阅读器的高度
        let currentPage = "";
        let currentHeight = 0;

        while (temp.firstChild) {
          const node = temp.firstChild;
          const clone = node.cloneNode(true);
          const testDiv = document.createElement("div");
          testDiv.style.cssText = `
              width: 1080px;
              font-size: 24px;
              line-height: 1.5;
              box-sizing: border-box;
          `;
          testDiv.appendChild(clone);
          document.body.appendChild(testDiv);
          const height = testDiv.offsetHeight;
          document.body.removeChild(testDiv);

          if (currentHeight + height > maxHeight && currentPage) {
            pages.push(currentPage);
            currentPage = "";
            currentHeight = 0;
          }

          currentPage += node.outerHTML || node.textContent;
          currentHeight += height;
          temp.removeChild(node);
        }

        if (currentPage) {
          pages.push(currentPage);
        }

        document.body.removeChild(temp);
        return pages;
      }

      // 生成预览图
      async function generatePreview(content) {
        const temp = document.createElement("div");
        temp.style.cssText = `
            width: 1080px;
            height: 1440px;
            padding: 40px;
            background: white;
            position: fixed;
            left: -9999px;
            top: 0;
            font-size: 24px;
            line-height: 1.5;
            box-sizing: border-box;
            overflow: hidden;
        `;
        temp.innerHTML = content;
        document.body.appendChild(temp);

        try {
          // 生成主图片
          const canvas = await html2canvas(temp, {
            width: 1080,
            height: 1440,
            scale: 1,
            useCORS: true,
            backgroundColor: "#ffffff",
          });

          // 生成缩略图
          const thumbCanvas = document.createElement("canvas");
          thumbCanvas.width = 200;
          thumbCanvas.height = 282;
          const thumbCtx = thumbCanvas.getContext("2d");
          thumbCtx.drawImage(canvas, 0, 0, 200, 282);

          // 将Data URL转换为File对象
          const normalFile = dataURLtoFile(
            canvas.toDataURL("image/jpeg", 0.9),
            `page-${Date.now()}.jpg`
          );
          const thumbFile = dataURLtoFile(
            thumbCanvas.toDataURL("image/jpeg", 0.7),
            `page-thumb-${Date.now()}.jpg`
          );

          return {
            normal: normalFile,
            thumb: thumbFile,
          };
        } catch (error) {
          throw error;
        } finally {
          document.body.removeChild(temp);
        }
      }

      // 辅助函数：将Data URL转换为File对象
      function dataURLtoFile(dataurl, filename) {
        const arr = dataurl.split(",");
        const mime = arr[0].match(/:(.*?);/)[1];
        const bstr = atob(arr[1]);
        let n = bstr.length;
        const u8arr = new Uint8Array(n);

        while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
        }

        return new File([u8arr], filename, { type: mime });
      }

      // 添加图片上传处理函数
      async function uploadImage(file) {
        try {
          const formData = new FormData();
          formData.append("image", file);
          formData.append("id", currentBookId);

          const response = await fetch("/admin/api/books/upload_image.php", {
            method: "POST",
            body: formData,
          });

          const result = await response.json();
          if (!result.success) throw new Error(result.message);

          return result.url; // 返回图片URL
        } catch (error) {
          console.error("图片上传失败:", error);
          throw error;
        }
      }

      function updatePreviewList(images) {
        const previewList = document.getElementById("previewList");
        previewList.innerHTML = "";

        if (!images || images.length === 0) {
          previewList.innerHTML = '<div class="preview-item">暂无预览图</div>';
          return;
        }

        images.forEach((image, index) => {
          // 处理新的图片对象格式
          const normalUrl = image.normal || image;
          const thumbUrl = image.thumb || image;

          previewList.innerHTML += `
            <div class="preview-item">
              <div class="page-title">第 ${index + 1} 页</div>
              <img src="${thumbUrl}?t=${Date.now()}" 
                   data-normal="${normalUrl}"
                   alt="第 ${index + 1} 页"
                   onclick="showFullImage(this)">
            </div>`;
        });
      }

      // 添加全屏查看图片的功能
      function showFullImage(img) {
        const fullScreen = document.createElement("div");
        fullScreen.className = "full-screen-image";
        fullScreen.innerHTML = `
          <img src="${img.dataset.normal}?t=${Date.now()}" alt="全屏图片">
        `;
        fullScreen.onclick = () => document.body.removeChild(fullScreen);
        document.body.appendChild(fullScreen);
      }

      // 初始化
      document.addEventListener("DOMContentLoaded", () => {
        initEditor();
        loadBooks();

        // 绑定保存按钮事件
        document.getElementById("btnSave").onclick = saveBook;

        // 确保封面上传事件监听器正确绑定
        const coverFileInput = document.getElementById("coverFile");
        if (coverFileInput) {
          coverFileInput.addEventListener("change", handleCoverUpload);
        }
      });

      // 封面上传处理函数
      async function handleCoverUpload() {
        if (!this.files || !this.files[0]) return;

        try {
          const formData = new FormData();
          formData.append("cover", this.files[0]);
          formData.append("id", currentBookId);

          const response = await fetch("/admin/api/books/upload_cover.php", {
            method: "POST",
            body: formData,
          });

          const result = await response.json();
          if (!result.success) throw new Error(result.message);

          // 更新封面显示
          document.querySelector(
            `.book-item[data-id="${currentBookId}"] .book-cover`
          ).src = result.url;

          // 更新预览区的封面
          const coverPreview = document.querySelector(
            "#previewList .preview-item:first-child img"
          );
          if (coverPreview) {
            coverPreview.src = result.url;
          }

          // 清空文件输入元素，防止保存时再次上传
          this.value = "";

          alert("封面设置成功！");
        } catch (error) {
          console.error("上传失败:", error);
          alert("上传失败，请重试");
        }
      }

      // 显示预览弹层
      async function showPreview() {
        if (!currentBookId) {
          alert("请先选择一本书");
          return;
        }

        const previewModal = document.getElementById("previewModal");
        previewModal.style.display = "block";

        // 获取编辑器内容
        const content = editor.root.innerHTML;

        try {
          // 分页处理内容
          const pages = splitContent(content);
          console.log(`内容已分为${pages.length}页`);

          // 初始化预览图数组
          let previewImages = [];

          // 为每一页生成预览图并上传
          for (let i = 0; i < pages.length; i++) {
            const pageImages = await generatePreview(pages[i]);

            // 使用表单格式提交数据
            const formData = new FormData();
            formData.append("id", currentBookId);
            formData.append("page", pageImages.normal, `page-${i + 1}.jpg`);
            formData.append(
              "thumb",
              pageImages.thumb,
              `page-thumb-${i + 1}.jpg`
            );

            const response = await fetch(
              "/admin/api/books/upload_preview.php",
              {
                method: "POST",
                body: formData,
              }
            );

            const result = await response.json();
            if (!result.success)
              throw new Error(result.message || "保存预览图失败");

            // 添加预览图URL到数组
            previewImages.push(result.urls.normal);
          }

          // 更新预览列表
          updatePreviewList(previewImages);
        } catch (error) {
          console.error("生成预览失败:", error);
          alert("生成预览失败，请重试: " + error.message);
          hidePreview();
        }
      }

      // 隐藏预览弹层
      function hidePreview() {
        const previewModal = document.getElementById("previewModal");
        previewModal.style.display = "none";
        // 清空预览列表
        document.getElementById("previewList").innerHTML = "";
      }

      // 点击弹层背景关闭
      document
        .getElementById("previewModal")
        .addEventListener("click", function (e) {
          if (e.target === this) {
            hidePreview();
          }
        });
    </script>

    <!-- 添加 html2canvas 库 -->
    <script src="../js/html2canvas.min.js"></script>
  </body>
</html>
